package com.hnkywl.sts.action.report;

import com.hnkywl.sts.entity.organ.Gsjg;
import com.hnkywl.sts.service.organ.GsjgService;
import com.hnkywl.sts.service.report.PjkcService;
import com.hnkywl.sts.util.POIUtil;
import net.ruixin.web.struts2.SimpleActionSupport;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.springframework.beans.factory.annotation.Autowired;

import java.text.DateFormat;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: Administrator
 * Date: 13-6-14
 * Time: 下午4:48
 * To change this template use File | Settings | File Templates.
 */
@Namespace("/report/pjkc")
public class PjkcAction extends SimpleActionSupport {
    private Long gsId;
    private Integer sftype;
    private Integer type;
    private Integer status;
    private Date startDate;
    private Date endDate;
    private int page;
    private int rows;
    private Integer year;
    private Integer month;
    private Date date;
    private Integer pjsflx;

    private PjkcService pjkcService;
    private GsjgService gsjgService;


    @Action("pjkc")
    public String pjkc() {
        date = new Date();
        return SUCCESS;
    }

    @Action("pjkc_detail")
    public String pjkcDetail() {
            if (year == null || month == null) {
            Calendar c = Calendar.getInstance();
            startDate = DateUtils.truncate(c.getTime(), 2);
            c.add(Calendar.MONTH, 1);
            c.add(Calendar.DATE, -1);
            endDate = DateUtils.truncate(c.getTime(), 2);
            c.setTime(endDate);
            c.add(Calendar.DATE, -1);
            endDate = c.getTime();
        } else {
            Calendar c = Calendar.getInstance();
            c.set(Calendar.YEAR, year);
            c.set(Calendar.MONTH, month - 1);
            startDate = DateUtils.truncate(c.getTime(), 2);
            c.add(Calendar.MONTH, 1);
            endDate = DateUtils.truncate(c.getTime(), 2);
            c.setTime(endDate);
            c.add(Calendar.DATE, -1);
            endDate = c.getTime();
        }
        return SUCCESS;
    }

    @Action("pjkcList")
    public void pjkcList() {
        String json = pjkcService.pjkcList(gsId, year, month, pjsflx);
        renderJson(json);
    }

    @Action("detailList")
    public void detailList() {
        renderJson(pjkcService.pjkcDetailList(gsId, sftype, type, status, startDate, endDate, page, rows));
    }

    @Action("exportDetail")
    public String exportDetail() {
        Map<String, Object> map = pjkcService.pjkcDetailListExport(gsId, sftype, type, status, startDate, endDate);
        List<Map> rows = (ArrayList) map.get("rows");
        List<Map> footer = (ArrayList) map.get("footer");

        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet("sheet1");
        POIUtil poiUtil = new POIUtil(wb);
        sheet.setDefaultRowHeightInPoints(21);
        sheet.setDefaultColumnWidth((short) 20);
        HSSFCellStyle headerStyle = poiUtil.createHeader3HSSFCellStyle(wb);
        Map<String, Object> options;
        if(status==0){
          options = exportOptions(sftype, type, status, gsId, startDate);
        }else{
            options = exportOptions(sftype, type, status, gsId, endDate);
        }
        List<String> columns = (List<String>) options.get("columns");
        List<String> columnName = (List<String>) options.get("columnName");
        List<Integer> columnScale = (List<Integer>) options.get("columnScale");
        String fileName = (String) options.get("fileName");

        poiUtil.fillRow(sheet, headerStyle, 0, columnName.toArray());
        for (int i = 1; i < rows.size() + 1; i++) {
            Map item = rows.get(i - 1);
            List<Object> data = new ArrayList<Object>();
            for (String col : columns) {
                data.add(item.get(col));
            }
            poiUtil.fillRowComplex(wb, sheet, null, i, columnScale, data.toArray());
        }
        //统计行
        if (footer != null) {
            HSSFCellStyle sumStyle = wb.createCellStyle();
            HSSFFont font = wb.createFont();
            font.setColor(HSSFFont.COLOR_RED);
            sumStyle.setFont(font);
            Map f = footer.get(0);
            List<Object> footerData = new ArrayList<Object>();
            for (String col : columns) {
                footerData.add(f.get(col));
            }
            poiUtil.fillRow(sheet, sumStyle, rows.size() + 1, footerData.toArray());
        }
        try {
            response.setContentType("application/x-download");
            String filedisplay = new String((fileName).getBytes("gb2312"), "iso8859-1");
            response.addHeader("Content-Disposition", "attachment;filename=" + filedisplay);
            wb.write(response.getOutputStream());
            response.getOutputStream().close();
        } catch (Exception e) {
            e.printStackTrace();
            renderText("位置异常，导出失败" + e.getMessage());
        }
        return null;
    }

    private Map<String, Object> exportOptions(Integer sftype, Integer type, Integer status, Long gsid, Date date) {

        List columns = new ArrayList();
        List columnName = new ArrayList();
        List columnScale = new ArrayList();
        String fileName = "";

        //sftype=0 应收票据
        if (sftype == 0) {
            String[] temp = {"gsmc", "pjlx", "pjhm", "sfkbm", "cpyh", "cprq", "dqr", "dqje", "cpr", "spr", "jpdw", "syrq", "bz"};
            columns = Arrays.asList(temp);
            temp = new String[]{"公司名称", "票据类型", "票据号码", "收款号码", "出票银行", "出票日", "到期日", "到期金额", "出票人", "收款人", "交款单位", "使用日期", "备注"};
            columnName = Arrays.asList(temp);
            Integer[] scale = {0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0};
            columnScale = Arrays.asList(scale);
            fileName = generateFileName(sftype, type, status, gsid, date);
        }
        //sftype=1 应付票据
        if (sftype == 1) {
            String[] temp = {"gsmc", "pjlx", "pjhm", "sfkbm", "cpyh", "cprq", "dqr", "dqje", "bzj", "yflx", "spr", "jpdw", "syrq", "bz"};
            columns = Arrays.asList(temp);
            temp = new String[]{"公司名称", "票据类型", "票据号码", "收款号码", "出票银行", "出票日", "到期日", "到期金额", "保证金", "应付利息", "收款人", "交款单位", "使用日期", "备注"};
            columnName = Arrays.asList(temp);
            Integer[] scale = {0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 0, 0, 0, 0};
            columnScale = Arrays.asList(scale);
            fileName = generateFileName(sftype, type, status, gsid, date);
        }

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("columns", columns);
        map.put("columnName", columnName);
        map.put("columnScale", columnScale);
        map.put("fileName", fileName);
        return map;
    }


    private String generateFileName(Integer sftype, Integer type, Integer status, Long gsid, Date date) {
        Gsjg gsjg = gsjgService.findGsjgDetail(gsid);
        DateFormat dateFormat = new java.text.SimpleDateFormat("yyyyMMddHHmmss");
        String s = dateFormat.format(new Date());
        Integer month = date.getMonth() + 1;
        String name = "";
        String sf = (sftype == 0 ? "应收" : "应付");
        String ypsp = "票据";
        String czzt = null;
        if (type == 0) ypsp = "银票";
        if (type == 1) ypsp = "商票";
        //0期初 1应收本期增加 2本期贴现 3本期托收 4本期背书 5本期兑换 6应付本期增加 7本期承兑 8本期支付 9期末
        switch (status) {
            case 0:
                czzt = "期初";
                break;
            case 1:
                czzt = "本期增加";
                break;
            case 2:
                czzt = "本期贴现";
                break;
            case 3:
                czzt = "本期托收";
                break;
            case 4:
                czzt = "本期背书";
                break;
            case 5:
                czzt = "本期兑换";
                break;
            case 6:
                czzt = "本期增加";
                break;
            case 7:
                czzt = "本期承兑";
                break;
            case 8:
                czzt = "本期支付";
                break;
            case 9:
                czzt = "期末";
                break;
            default:
                czzt = "";
        }
        name = gsjg.getJc() + "_" + month + "月" + sf + ypsp + czzt + "_" + s + ".xls";
        return name;
    }

    //=================setter getter==============
    public Long getGsId() {
        return gsId;
    }

    public void setGsId(Long gsId) {
        this.gsId = gsId;
    }

    public Integer getSftype() {
        return sftype;
    }

    public void setSftype(Integer sftype) {
        this.sftype = sftype;
    }

    public Integer getType() {
        return type;
    }

    public void setType(Integer type) {
        this.type = type;
    }

    public Integer getStatus() {
        return status;
    }

    public void setStatus(Integer status) {
        this.status = status;
    }

    public Date getStartDate() {
        return startDate;
    }

    public void setStartDate(Date startDate) {
        this.startDate = startDate;
    }

    public Date getEndDate() {
        return endDate;
    }

    public void setEndDate(Date endDate) {
        this.endDate = endDate;
    }

    public int getPage() {
        return page;
    }

    public void setPage(int page) {
        this.page = page;
    }

    public int getRows() {
        return rows;
    }

    public void setRows(int rows) {
        this.rows = rows;
    }

    public Integer getYear() {
        return year;
    }

    public void setYear(Integer year) {
        this.year = year;
    }

    public Integer getMonth() {
        return month;
    }

    public void setMonth(Integer month) {
        this.month = month;
    }

    public PjkcService getPjkcService() {
        return pjkcService;
    }

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }

    public Integer getPjsflx() {
        return pjsflx;
    }

    public void setPjsflx(Integer pjsflx) {
        this.pjsflx = pjsflx;
    }

    //=================setter===================
    @Autowired
    public void setPjkcService(PjkcService pjkcService) {
        this.pjkcService = pjkcService;
    }

    @Autowired
    public void setGsjgService(GsjgService gsjgService) {
        this.gsjgService = gsjgService;
    }
}
